package com.tobeing.voicechat.customs;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.rtp.AudioStream;
import android.util.Log;

import java.io.IOException;

/**
 * Created by Administrator on 2017/10/31/031.
 */

public class RecorderPlay {
    private static MediaPlayer mMediaPlayer;
    private static PlayCompletionListener mPlayCompletionListener;

    public static void startPaly(String path, PlayCompletionListener listener) {
        Log.i("play path", path);
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    mMediaPlayer.reset();
                    return false;
                }
            });
        } else {
            if(mPlayCompletionListener != null){
                mPlayCompletionListener.completed();
            }
            mMediaPlayer.reset();
        }
        try {
            mPlayCompletionListener = listener;
            mMediaPlayer.setDataSource(path);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    if(mPlayCompletionListener != null){
                        mPlayCompletionListener.completed();
                    }
                }
            });
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void onPause() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
        }
    }

    public static void onResume() {
        if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
            mMediaPlayer.start();
        }
    }

    public static void release() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }

    public interface PlayCompletionListener{
        void completed();
    }
}
